package org.jeecg.modules.wflow.workflow.config;

import cn.hutool.core.util.StrUtil;
import org.jeecg.modules.wflow.config.AsyncTaskTheadPoolConfig;
import org.jeecg.modules.wflow.workflow.bean.dto.NotifyDto;
import org.jeecg.modules.wflow.workflow.bean.process.props.ApprovalProps;
import org.jeecg.modules.wflow.workflow.service.NotifyService;
import org.jeecg.modules.wflow.workflow.service.ProcessNodeCatchService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.common.engine.api.delegate.event.FlowableEngineEntityEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.AbstractFlowableEngineEventListener;
import org.flowable.engine.delegate.event.FlowableProcessStartedEvent;
import org.flowable.engine.delegate.event.FlowableSequenceFlowTakenEvent;
import org.flowable.engine.delegate.event.impl.FlowableProcessEventImpl;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @author : willian fu
 * @date : 2022/8/27
 */
@Slf4j
@Component
public class GlobalTaskListener extends AbstractFlowableEngineEventListener {

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private RuntimeService runtimeService;

    @Override
    protected void taskCreated(FlowableEngineEntityEvent event) {
        log.info("监听到任务[{}]创建", event.getExecutionId());
        super.taskCreated(event);
    }

    @Override
    protected void taskCompleted(FlowableEngineEntityEvent event) {
        log.info("监听到任务[{}]结束", event.getExecutionId());
        super.taskCompleted(event);
    }

    @Override
    protected void processCompleted(FlowableEngineEntityEvent event) {
        AsyncTaskTheadPoolConfig.executor.submit(() -> {
            ProcessInstance instance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(event.getProcessInstanceId())
                    .singleResult();
            notifyService.notify(NotifyDto.builder()
                    .target(instance.getStartUserId())
                    .instanceId(event.getProcessInstanceId())
                    .processDefId(event.getProcessDefinitionId())
                    .title("您的审批已通过")
                    .type(NotifyDto.TypeEnum.SUCCESS)
                    .content(StrUtil.builder("您提交的审批【",
                            instance.getProcessDefinitionName(), "】已经通过").toString())
                    .build());
            log.info("[{}]审批流程[{}}]通过", instance.getProcessInstanceId(), instance.getProcessDefinitionName());
        });
        super.processCompleted(event);
    }
}
